package com.gitee.leijin.rbac.security;


import cn.hutool.core.collection.CollUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

@Component
public class RbacManager {

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    public boolean hasPermission(HttpServletRequest request) {
        boolean hasPermission = false;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if (principal instanceof SecurityUser) {
            SecurityUser securityUser = (SecurityUser) principal;
            Set<String> authorizedUris = securityUser.getAuthorizedUris();
            if (CollUtil.isEmpty(authorizedUris)) {
                return false;
            }
            for (String uri : authorizedUris) {
                if (antPathMatcher.match(uri, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
            return hasPermission;
        }
        return false;
    }
}
